import axios from 'axios'; 
import { ElMessage } from 'element-plus';
import router from '@/router';

const http = axios.create({
   baseURL: 'http://localhost:8081',
   withCredentials: true
});

http.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  response => {
    if (response.data && response.data.code) {
      if (response.data.code === 401) {
        ElMessage.error(response.data.message || '未登录或登录已过期');
        router.push('/login');
        return Promise.reject(new Error(response.data.message || '未登录或登录已过期'));
      }
    }
    return response;
  },
  error => {
    if (error.response) {
      if (error.response.status === 401) {
        ElMessage.error('未登录或登录已过期');
        router.push('/login');
      } else if (error.response.status === 403) {
        ElMessage.error(error.response.data?.message || '您没有权限执行此操作');
        return Promise.reject(error);
      } else {
        ElMessage.error(error.response.data?.message || '请求失败');
      }
    } else {
      ElMessage.error('网络错误，请稍后重试');
    }
    return Promise.reject(error);
  }
);

function urlFormater(url, params) {
  if (params) {
    let paramList = [];
    for (let key in params) {
      paramList.push(key + '=' + encodeURIComponent(params[key]));
    }
    return url.indexOf('?') > -1 ? (url + '&' + paramList.join('&')) : (url + '?' + paramList.join('&'));
  }
  return url;
}

function mixinCustom(config) {
  config.custom = Object.assign({
    toast: true,
    catch: true,
    loading: true,
  }, config.custom || {});
  return config;
}

const request = {
  post(url, params, config = {}) {
    return http.post(url, params, config);
  },
  get(url, params, config = {}) {
    config = mixinCustom(config);
    if (params && params.params) {
      return http.get(url, params);
    } else {
      let path = urlFormater(url, params);
      return http.get(path, config);
    }
  },
  put(url, params, config = {}) {
    return http.put(url, params, config);
  },
  delete(url, params, config = {}) {
    return http.delete(url, { data: params, ...config });
  },
};

export default request;